package bb.lanxing.activity.routebook;

import static bb.lanxing.common.config.Constants.LUSHU_BAIDU_FILE_SUFFIX;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.blankj.utilcode.util.FileUtils;
import com.tencent.open.SocialOperation;
import com.umeng.analytics.MobclickAgent;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.base.BaseActivity;
import bb.lanxing.activity.sport.SportActivity;
import bb.lanxing.common.config.Constants;
import bb.lanxing.common.config.UmengEventConst;
import bb.lanxing.lib.devices.sgsettingentity.routebook.Route;
import bb.lanxing.lib.devices.sgsettingentity.routebook.Routebooks;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.model.database.RouteBook;
import bb.lanxing.model.database.Waypoint;
import bb.lanxing.model.database.Workout;
import bb.lanxing.model.event.RouteBookEvent;
import bb.lanxing.network.BiCiCallback;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.util.AppFileUtils;
import bb.lanxing.util.BusProvider;
import bb.lanxing.util.RouteBookUtil;
import bb.lanxing.util.SportTypeResUtil;
import bb.lanxing.util.ui.InputHelper;
import bb.lanxing.view.BiciAlertDialogBuilder;
import bb.lanxing.view.PopupMenu;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class RouteBookEditActivity extends BaseActivity {
    private TextView commitBtn;
    private TextView descriptionView;
    private boolean fromCreate = false;
    private RouteBook routeBook;
    private RelativeLayout lushuLineLayout;
    private TextView lushuTitleView;
    private ImageView lushuTypeArrow;
    private TextView lushuTypeView;
    private View mCommitBtn;
    private View mDeleteBtn;
    private View mLushuLineLayout;
    private View mLushuTypeLayout;
    private LinearLayout middleLayout;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lushu_edit);
        bindView(getWindow().getDecorView());
        setupActionBar(true);
        long longExtra = getIntent().getLongExtra(SportActivity.EXTRA_LUSHU_ID, -1L);
        this.fromCreate = getIntent().getBooleanExtra("from_create", false);
        RouteBook byId = RouteBook.getById(longExtra);
        this.routeBook = byId;
        if (byId == null) {
            finish();
        } else {
            initView();
            checkIfNotExistOnRouteBooks(byId.getServerId());
        }
    }

    private void initView() {
        if (fromCreate) {
            setTitle(getString(R.string.label_lushu_upload));
            this.lushuTitleView
                    .setText(getString(R.string.from_to, routeBook.getStartAddress(), routeBook.getEndAddress()));
        }
        if (!TextUtils.isEmpty(this.routeBook.getTitle()) && !this.fromCreate) {
            this.lushuTitleView.setText(this.routeBook.getTitle());
        }
        if (!TextUtils.isEmpty(this.routeBook.getDescription())) {
            this.descriptionView.setText(this.routeBook.getDescription());
        }
        this.lushuLineLayout.setVisibility(View.GONE);
        if (this.fromCreate) {
            this.routeBook.setSport(Workout.TYPE_OTHER);
            this.lushuTypeView.setText(R.string.lushu_edit_toast_empty_sport_type);
        } else {
            this.lushuTypeView.setText(SportTypeResUtil.getTypeTextRes(this.routeBook.getSport()));
        }
        if ((this.routeBook.getSourceType() == RouteBook.TYPE_GOOGLE
                || this.routeBook.getSourceType() == RouteBook.TYPE_BAIDU) && this.routeBook.getUserId() > 0
                && this.routeBook.getUserId() == SharedManager.getInstance().getUserId()
                && this.routeBook.isUploadEnable()) {
            this.commitBtn.setText(R.string.lushu_edit_btn_save_upload);
            this.middleLayout.setVisibility(View.VISIBLE);
            return;
        }
        this.commitBtn.setText(R.string.lushu_edit_btn_save);
        this.middleLayout.setVisibility(View.GONE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == Constants.REQUEST_CODE) {
            this.routeBook = RouteBook.getById(this.routeBook.getId());
            setResult(Constants.RESULT_CODE_LUSHU_EDIT);
        }
    }

    private void onTypeClick() {
        showTypeOption();
    }

    private void onLineClick() {
        Intent intent = new Intent(this, BaiduRouteBookCreateActivity.class);
        intent.putExtra("launch_mode", 1);
        intent.putExtra(SportActivity.EXTRA_LUSHU_ID, this.routeBook.getId());
        startActivityForResult(intent, 76);
    }

    private void onDeleteClick() {
        showDeleteDialog();
    }

    private void commitBtnClick() {
        int sport = this.routeBook.getSport();
        if (sport != Workout.TYPE_RUNNING && sport != Workout.TYPE_CYCLING && sport != Workout.TYPE_WALKING) {
            toast(R.string.lushu_edit_toast_empty_sport_type);
            return;
        }
        String charSequence = this.lushuTitleView.getText().toString();
        if (TextUtils.isEmpty(charSequence)) {
            App.getContext().showMessage(R.string.lushu_edit_toast_empty_title);
            this.lushuTitleView.findFocus();
            return;
        }
        this.routeBook.setTitle(charSequence);
        this.routeBook.setDescription(this.descriptionView.getText().toString());
        this.routeBook.setWayPoints(Waypoint.getByLushuId(this.routeBook.getId()));
        this.routeBook.setUserAvatar(App.getContext().getSigninUser().getPhotoUrl());
        this.routeBook.save();
        setResult(Constants.RESULT_CODE_LUSHU_EDIT);
        long userId = routeBook.getUserId();
        if (userId > 0 && userId == SharedManager.getInstance().getUserId()) {
            uploadRouteBook(this.routeBook);
            return;
        }
        App.getContext().showMessage(R.string.toast_save_successful);
        finish();
    }

    @Override
    public boolean onHomeBack() {
        InputHelper.hideSoftInput(this);
        return super.onHomeBack();
    }

    private void showTypeOption() {
        PopupMenu popupMenu = new PopupMenu(this, this.lushuTypeArrow);
        popupMenu.getMenuInflater().inflate(R.menu.menu_sport_type, popupMenu.getMenu());
        MenuItem findItem = popupMenu.getMenu().findItem(R.id.training);
        MenuItem findItem2 = popupMenu.getMenu().findItem(R.id.swimming);
        MenuItem findItem3 = popupMenu.getMenu().findItem(R.id.skiing);
        MenuItem findItem4 = popupMenu.getMenu().findItem(R.id.other);
        MenuItem findItem5 = popupMenu.getMenu().findItem(R.id.indoorbike);
        MenuItem findItem6 = popupMenu.getMenu().findItem(R.id.crosstrainer);

        findItem.setVisible(false);
        findItem2.setVisible(false);
        findItem3.setVisible(false);
        findItem4.setVisible(false);
        findItem5.setVisible(false);
        findItem6.setVisible(false);
        popupMenu.show();
        popupMenu.setOnMenuItemClickListener(item -> {
            int itemId = item.getItemId();
            if (itemId == R.id.running) {
                routeBook.setSport(Workout.TYPE_RUNNING);
            } else if (itemId == R.id.walking) {
                routeBook.setSport(Workout.TYPE_WALKING);
            } else {
                routeBook.setSport(Workout.TYPE_CYCLING);
            }
            lushuTypeView.setText(SportTypeResUtil.getTypeTextRes(routeBook.getSport()));
            return true;
        });
    }

    private void showDeleteDialog() {
        new BiciAlertDialogBuilder(this).setTitle(R.string.lushu_edit_dialog_title_delete)
                .setMessage(R.string.lushu_edit_dialog_content_delete)
                .setPositiveButton(R.string.delete, (dialog, which) -> doDelete())
                .setNegativeButton(R.string.not_delete, (dialog, which) -> {
                }).show();
    }

    private void checkIfNotExistOnRouteBooks(long serverId) {
        showLoadingDialog(R.string.loading, false);
        new Thread(() -> {
            Routebooks routebooks =
                    com.besall.allbase.common.utils.FileUtils.parseRouteBooksJson(RouteBookEditActivity.this);
            boolean shouldHide = false;
            if (null != routebooks) {
                List<Route> routeList = routebooks.routes;
                if (!routeList.isEmpty()) {
                    for (Route route : routeList) {
                        if (route.getRid().equals(String.valueOf(serverId))) {
                            shouldHide = true;
                            break;
                        }
                    }
                }
            }

            boolean finalShouldHide = shouldHide;
            runOnUiThread(() -> {
                dismissLoadingDialog();
                if (finalShouldHide) {
                    mDeleteBtn.setVisibility(View.GONE);
                }
            });
        }).start();
    }

    public void doDelete() {
        if (routeBook == null) {
            return;
        }
        if (!routeBook.isUploadEnable() || !this.routeBook.isUpload() || this.routeBook.getServerType() == 2) {
            if (RouteBookUtil.deleteRouteBook(this.routeBook)) {
                File folder = new File(AppFileUtils.buildExternalDirectoryPath(Constants.LUSHU_DIRECTION_UPLOAD));
                // 删除文件夹下所有的文件内容,这个是临时的文件
                FileUtils.deleteAllInDir(folder);
                App.getContext().showMessage(R.string.toast_delete_successful);
                setResult(Constants.RESULT_CODE_LUSHU_DELETE,
                        new Intent().putExtra(SportActivity.EXTRA_LUSHU_ID, this.routeBook.getId()));
                BusProvider.getInstance().post(new RouteBookEvent(0, this.routeBook.getServerId()));
                finish();
                return;
            }
            App.getContext().showMessage(R.string.toast_delete_failed);
            return;
        }
        MyHttpClient.deleteLushuById(this.routeBook.getServerId(), new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                App.getContext().showMessage(R.string.toast_delete_failed);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                if (response.isSuccessful() && RouteBookUtil.deleteRouteBook(routeBook)) {
                    BusProvider.getInstance().post(new RouteBookEvent(0, routeBook.getServerId()));
                    App.getContext().showMessage(R.string.toast_delete_successful);
                    setResult(Constants.RESULT_CODE_LUSHU_DELETE,
                            new Intent().putExtra(SportActivity.EXTRA_LUSHU_ID, routeBook.getId()));
                    finish();
                    return;
                }
                App.getContext().showMessage(R.string.toast_delete_failed);
            }
        });
    }

    private void uploadRouteBook(final RouteBook routeBook) {
        showLoadingDialog(R.string.dialog_uploading, false);
        MobclickAgent.onEventValue(this, UmengEventConst.LUSHU_UPLOAD, null, 1);
        String str = routeBook.getUuid() + LUSHU_BAIDU_FILE_SUFFIX;
        String buildExternalDirectoryPath = AppFileUtils.buildExternalDirectoryPath(Constants.LUSHU_DIRECTION_UPLOAD);
        File parent = new File(buildExternalDirectoryPath);
        File file = new File(parent, str);
        if (file.exists()) {
            MyHttpClient.uploadLushu2(routeBook, str, file, new BiCiCallback() {
                @Override
                public void onResponseString(@NonNull String str3) {
                    try {
                        JSONObject jSONObject = new JSONObject(str3).getJSONObject("data");
                        routeBook.setServerId(jSONObject.getLong("serverId"));
                        routeBook.setIsUpload(true);
                        ContentValues contentValues = new ContentValues();
                        contentValues.put("serverId", routeBook.getServerId());
                        contentValues.put("isupload", routeBook.isUpload());
                        routeBook.update(contentValues);
                        // 删除文件夹下所有的文件内容,这个是临时的文件
                        FileUtils.deleteAllInDir(parent);
                        runOnUiThread(() -> {
                            dismissLoadingDialog();
                            toast(R.string.toast_upload_successful);
                            finish();
                        });
                    } catch (JSONException e) {
                        onResponseFail(e.getMessage());
                        e.printStackTrace();
                    }
                }

                @Override
                public void onResponseFail(String str3) {
                    super.onResponseFail(str3);
                    ((BaseActivity) context).dismissLoadingDialog();
                }
            });
            // requestGetAliOssToken(str, buildExternalDirectoryPath, file, textView, lushu);
        } else {
            if (!routeBook.isUpload()) {
                dismissLoadingDialog();
                snack(R.string.st_lushu_file_not_exist);
            } else {
                requestSaveRouteBook(file);
            }
        }
    }

    private void requestGetAliOssToken(final String fileName, final String dirFilePath, final File file) {
        MyHttpClient.getRouteBookToken(new BiCiCallback() {
            @Override
            public void onResponseString(@NonNull String string) {
                try {
                    JSONObject jSONObject = new JSONObject(string).getJSONObject("data");
                    String string2 = jSONObject.getString(/* UMCommonContent.bp */"policy");
                    String string3 = jSONObject.getString(SocialOperation.GAME_SIGNATURE);
                    String string4 = jSONObject.getString("accessid");
                    String string5 = jSONObject.getString("host");
                    if (file.exists()) {
                        requestUploadOss(string5, string4, string3, string2, dirFilePath, fileName, file);
                    } else {
                        requestSaveRouteBook(file);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onResponseFail(String errMsg) {
                super.onResponseFail(errMsg);
                dismissLoadingDialog();
            }
        }, fileName);
    }

    public void requestUploadOss(String url, String ossAccessKey, String signature, String policy, String dircFilePath,
            String fileName, final File file) {
        MyHttpClient.uploadLushu2AliOss(new BiCiCallback() {
            @Override
            public void onResponseString(@NonNull String string) {
                requestSaveRouteBook(file);
            }

            @Override
            public void onResponseFail(String errMsg) {
                super.onResponseFail(errMsg);
                dismissLoadingDialog();
            }
        }, url, ossAccessKey, signature, policy, dircFilePath, fileName);
    }

    private void requestSaveRouteBook(final File jsonFile) {
        MyHttpClient.editLushu(routeBook, new BiCiCallback() {

            @Override
            public void onResponseString(@NonNull String string) {
                try {
                    routeBook.setServerId(new JSONObject(string).getJSONObject("data").getLong("serverId"));
                    routeBook.setIsUpload(true);
                    routeBook.save();
                    if (jsonFile.exists()) {
                        jsonFile.delete();
                    }
                    runOnUiThread(() -> {
                        dismissLoadingDialog();
                        toast(R.string.toast_upload_successful);
                        finish();
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onResponseFail(String errMsg) {
                super.onResponseFail(errMsg);
                dismissLoadingDialog();
            }
        });
    }

    private void bindView(View bindSource) {
        this.lushuTitleView = bindSource.findViewById(R.id.lushuTitleView);
        this.descriptionView = bindSource.findViewById(R.id.descriptionView);
        this.lushuTypeView = bindSource.findViewById(R.id.lushuTypeView);
        this.lushuTypeArrow = bindSource.findViewById(R.id.lushuTypeArrow);
        this.middleLayout = bindSource.findViewById(R.id.middleLayout);
        this.lushuLineLayout = bindSource.findViewById(R.id.lushuLineLayout);
        this.commitBtn = bindSource.findViewById(R.id.commitBtn);
        this.mLushuTypeLayout = bindSource.findViewById(R.id.lushuTypeLayout);
        this.mLushuLineLayout = bindSource.findViewById(R.id.lushuLineLayout);
        this.mDeleteBtn = bindSource.findViewById(R.id.deleteBtn);
        this.mCommitBtn = bindSource.findViewById(R.id.commitBtn);
        this.mLushuTypeLayout.setOnClickListener(view -> onTypeClick());
        this.mLushuLineLayout.setOnClickListener(view -> onLineClick());
        this.mDeleteBtn.setOnClickListener(view -> onDeleteClick());
        this.mCommitBtn.setOnClickListener(view -> commitBtnClick());
    }
}
